package com.example.managemyself.ui.pomodoro;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.managemyself.R;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.viewmodel.PomodoroViewModel;
import com.example.managemyself.viewmodel.TaskViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 番茄钟Fragment，处理番茄钟UI逻辑
 */
public class PomodoroFragment extends Fragment {

    private PomodoroViewModel pomodoroViewModel;
    private TaskViewModel taskViewModel;
    private TextView tvTimer;
    private TextView tvStatus;
    private TextView tvCompletedCount;
    private Button btnStart;
    private Button btnPause;
    private Button btnReset;
    private Button btnCompleteTask;
    private Spinner spinnerWorkTime;
    private Spinner spinnerBreakTime;
    private Spinner spinnerTasks;
    private ProgressBar progressBar;
    private List<Task> uncompletedTasks = new ArrayList<>();
    
    // 保存选中的任务位置，用于页面恢复
    private int selectedTaskPosition = 0;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_pomodoro, container, false);
        
        // 初始化视图
        tvTimer = root.findViewById(R.id.tvTimer);
        tvStatus = root.findViewById(R.id.tvStatus);
        tvCompletedCount = root.findViewById(R.id.tvCompletedCount);
        btnStart = root.findViewById(R.id.btnStart);
        btnPause = root.findViewById(R.id.btnPause);
        btnReset = root.findViewById(R.id.btnReset);
        btnCompleteTask = root.findViewById(R.id.btnCompleteTask);
        spinnerWorkTime = root.findViewById(R.id.spinnerWorkTime);
        spinnerBreakTime = root.findViewById(R.id.spinnerBreakTime);
        spinnerTasks = root.findViewById(R.id.spinnerTasks);
        progressBar = root.findViewById(R.id.progressBar);
        
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化ViewModel
        pomodoroViewModel = new ViewModelProvider(this).get(PomodoroViewModel.class);
        taskViewModel = new ViewModelProvider(requireActivity()).get(TaskViewModel.class);

        setupTimeSpinners();
        setupButtons();
        setupTaskSpinner();
        observePomodoroViewModel();
        observeTaskViewModel();
    }

    private void setupTimeSpinners() {
        // 设置工作时间选项
        String[] workTimeOptions = {"15分钟", "20分钟", "25分钟", "30分钟", "45分钟", "60分钟"};
        ArrayAdapter<String> workTimeAdapter = new ArrayAdapter<>(
                requireContext(), android.R.layout.simple_spinner_item, workTimeOptions);
        workTimeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerWorkTime.setAdapter(workTimeAdapter);
        spinnerWorkTime.setSelection(2); // 默认选择25分钟
        
        // 设置休息时间选项
        String[] breakTimeOptions = {"3分钟", "5分钟", "10分钟", "15分钟"};
        ArrayAdapter<String> breakTimeAdapter = new ArrayAdapter<>(
                requireContext(), android.R.layout.simple_spinner_item, breakTimeOptions);
        breakTimeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerBreakTime.setAdapter(breakTimeAdapter);
        spinnerBreakTime.setSelection(1); // 默认选择5分钟
        
        // 设置工作时间选择监听器
        spinnerWorkTime.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
                int minutes;
                switch (position) {
                    case 0: minutes = 15; break;
                    case 1: minutes = 20; break;
                    case 2: minutes = 25; break;
                    case 3: minutes = 30; break;
                    case 4: minutes = 45; break;
                    case 5: minutes = 60; break;
                    default: minutes = 25;
                }
                pomodoroViewModel.setWorkTimeInMinutes(minutes);
            }
            
            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {
            }
        });
        
        // 设置休息时间选择监听器
        spinnerBreakTime.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
                int minutes;
                switch (position) {
                    case 0: minutes = 3; break;
                    case 1: minutes = 5; break;
                    case 2: minutes = 10; break;
                    case 3: minutes = 15; break;
                    default: minutes = 5;
                }
                pomodoroViewModel.setBreakTimeInMinutes(minutes);
            }
            
            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {
            }
        });
    }

    private void setupButtons() {
        // 设置按钮点击事件
        btnStart.setOnClickListener(v -> {
            if (pomodoroViewModel.getAssociatedTask().getValue() == null) {
                Toast.makeText(getContext(), "请先选择一个关联任务", Toast.LENGTH_SHORT).show();
            } else {
                pomodoroViewModel.startTimer();
            }
        });
        btnPause.setOnClickListener(v -> pomodoroViewModel.pauseTimer());
        btnReset.setOnClickListener(v -> pomodoroViewModel.stopTimer());
        btnCompleteTask.setOnClickListener(v -> {
            if (pomodoroViewModel.getAssociatedTask().getValue() != null) {
                showCompleteTaskDialog(pomodoroViewModel.getAssociatedTask().getValue());
            }
        });
    }

    private void setupTaskSpinner() {
        spinnerTasks.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedTaskPosition = position; // 保存选中位置
                
                if (position > 0) { // Position 0 is the hint
                    Task selectedTask = uncompletedTasks.get(position - 1);
                    pomodoroViewModel.setAssociatedTask(selectedTask);
                    // 显示完成任务按钮
                    btnCompleteTask.setVisibility(View.VISIBLE);
                } else {
                    pomodoroViewModel.setAssociatedTask(null);
                    // 隐藏完成任务按钮
                    btnCompleteTask.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                pomodoroViewModel.setAssociatedTask(null);
                btnCompleteTask.setVisibility(View.GONE);
                selectedTaskPosition = 0;
            }
        });
    }

    private void observeTaskViewModel() {
        taskViewModel.getAllTasks().observe(getViewLifecycleOwner(), tasks -> {
            // 只筛选学习类型且未完成的任务
            uncompletedTasks = tasks.stream()
                    .filter(t -> !t.isCompleted() && "学习".equals(t.getType()))
                    .collect(Collectors.toList());
            
            List<String> taskNames = new ArrayList<>();
            taskNames.add("选择一个学习任务...");
            uncompletedTasks.forEach(t -> taskNames.add(t.getTitle()));

            ArrayAdapter<String> tasksAdapter = new ArrayAdapter<>(
                    requireContext(), android.R.layout.simple_spinner_item, taskNames);
            tasksAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerTasks.setAdapter(tasksAdapter);
            
            // 如果当前选择的任务不在新的列表中，重置选择
            Task currentTask = pomodoroViewModel.getAssociatedTask().getValue();
            if (currentTask != null && !uncompletedTasks.contains(currentTask)) {
                pomodoroViewModel.setAssociatedTask(null);
                btnCompleteTask.setVisibility(View.GONE);
                spinnerTasks.setSelection(0);
            }
        });
    }

    private void observePomodoroViewModel() {
        // 观察剩余时间
        pomodoroViewModel.getTimeLeftInMillis().observe(getViewLifecycleOwner(), timeLeft -> {
            tvTimer.setText(pomodoroViewModel.formatTime(timeLeft));
            progressBar.setProgress(pomodoroViewModel.getProgress());
        });

        // 观察计时器状态
        pomodoroViewModel.getTimerState().observe(getViewLifecycleOwner(), state -> {
            updateUIBasedOnState(state);
            if (state == PomodoroViewModel.TimerState.BREAKING) {
                // After work session finishes, before break starts
                Task completedTask = pomodoroViewModel.getAssociatedTask().getValue();
                if (completedTask != null && !completedTask.isCompleted()) {
                    showCompleteTaskDialog(completedTask);
                }
            }
        });

        // 观察完成的番茄钟数量
        pomodoroViewModel.getCompletedPomodoros().observe(getViewLifecycleOwner(), count -> {
            tvCompletedCount.setText(String.valueOf(count));
        });
    }

    private void updateUIBasedOnState(PomodoroViewModel.TimerState state) {
        switch (state) {
            case IDLE:
                tvStatus.setText("准备开始");
                btnStart.setEnabled(true);
                btnPause.setEnabled(false);
                btnReset.setEnabled(false);
                btnCompleteTask.setEnabled(pomodoroViewModel.getAssociatedTask().getValue() != null);
                spinnerTasks.setEnabled(true);
                spinnerWorkTime.setEnabled(true);
                spinnerBreakTime.setEnabled(true);
                break;
            case WORKING:
                tvStatus.setText("工作中");
                btnStart.setEnabled(false);
                btnPause.setEnabled(true);
                btnReset.setEnabled(true);
                btnCompleteTask.setEnabled(pomodoroViewModel.getAssociatedTask().getValue() != null);
                spinnerTasks.setEnabled(false);
                spinnerWorkTime.setEnabled(false);
                spinnerBreakTime.setEnabled(false);
                break;
            case PAUSED:
                tvStatus.setText("已暂停");
                btnStart.setEnabled(true);
                btnPause.setEnabled(false);
                btnReset.setEnabled(true);
                btnCompleteTask.setEnabled(pomodoroViewModel.getAssociatedTask().getValue() != null);
                spinnerTasks.setEnabled(false);
                spinnerWorkTime.setEnabled(false);
                spinnerBreakTime.setEnabled(false);
                break;
            case BREAKING:
                tvStatus.setText("休息中");
                btnStart.setEnabled(false);
                btnPause.setEnabled(true);
                btnReset.setEnabled(true);
                btnCompleteTask.setEnabled(false);
                spinnerTasks.setEnabled(false);
                spinnerWorkTime.setEnabled(false);
                spinnerBreakTime.setEnabled(false);
                break;
        }
    }

    private void showCompleteTaskDialog(Task task) {
        new AlertDialog.Builder(getContext())
                .setTitle("番茄钟完成")
                .setMessage("你已完成一个番茄钟，要将任务 \"" + task.getTitle() + "\" 标记为已完成吗？")
                .setPositiveButton("完成", (dialog, which) -> {
                    task.setCompleted(true);
                    taskViewModel.updateTask(task);
                    
                    // 通知日记系统任务已完成
                    com.example.managemyself.util.TaskCompletionNotifier.getInstance().notifyTaskCompleted(task);
                    
                    Toast.makeText(getContext(), "任务已标记为完成", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("不了", null)
                .show();
    }
}
